<template>
  <view>
    <GoSearch />
    <Tabs @change="changeTab" :list="tabList" :current="currentIndex" />
    <GoodsItem v-for="item in goodsList" :key="item.goods_id" :data="item" />
  </view>
</template>

<script>
import Tabs from './components/Tabs.vue';
import GoodsItem from './components/GoodsItem.vue';

let params = {
  // 商品Id
  cid: '',
  // 查询
  query: '',
  // 页面号
  pagenum: 1,
  pagesize: 10,
};
let isFinished = false;

export default {
  components: { Tabs, GoodsItem },
  data() {
    return {
      tabList: [{ name: '综合' }, { name: '销量' }, { name: '价格' }],
      currentIndex: 0,
      goodsList: [],
    };
  },
  // 生命周期：加载页面
  onLoad(options) {
    params = {
      cid: '',
      query: '',
      pagenum: 1,
      pagesize: 10,
    };
    totalPage = 0;
    isFinished = false;
    params.cid = options.cid;
    this.getGoods();
  },
  // 生命周期：监听上拉到底
  onReachBottom() {
    if (isFinished) {
      uni.showToast({
        title: '已经加载完毕！',
        icon: 'none',
      });
      return;
    }
    // 实现下拉更新页
    // 1、翻页：页码加一
    params.pagenum++;
    // 2、发送请求
    this.getGoods();
    // 3、数据处理
    // 3.1：旧数据不影响
    // 3.2：新数据直接在旧数据下面更新
  },
  // 生命周期：监听上拉刷新
  async onPullDownRefresh() {
    this.goodsList = [];
    params.pagenum = 1;
    await this.getGoods();
    uni.stopPullDownRefresh();
    isFinished = false;
  },

  methods: {
    changeTab(index) {
      this.currentIndex = index;
    },

    async getGoods() {
      const { message } = await this.$u.get('/goods/search', params);
      this.goodsList = [...this.goodsList, ...message.goods];

      if (message.goods.length < params.pagesize) {
        isFinished = true;
      }
    },
  },
};
</script>

<style lang="scss" scoped></style>
